package com.repository;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.model.Book;
import com.model.Category;
import com.repository.config.DataSourceUtil;

public class BookRepositoryImpl implements BookRepository {
	Connection conn;// 声明连接对象
	QueryRunner run;// 声明dbutils对象

	public BookRepositoryImpl() throws SQLException {
		this.conn = DataSourceUtil.getDataSource().getConnection();
		this.run = new QueryRunner();
	}

	//查询所有图书
	public List<Book> getBook() {
		try {
			return run.query(conn, "select * from book", new BeanListHandler<Book>(Book.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	//查询图书的所有分类
	public List<Category> getCategory() {
		try {
			return run.query(conn, "select * from category", new BeanListHandler<Category>(Category.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	//新增图书
	public int addBook(Book book) {
		try {
			return run.update(conn, "insert into book(name,author,`describe`,price,category_id) values(?,?,?,?,?)",
					book.getName(), book.getAuthor(), book.getDescribe(), book.getPrice(), book.getCategory_id());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return -1;
	}

	@Override
	public int delBook(long bookId) {
		try {
			return run.update(conn, "delete from book where id = ?", bookId);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return -1;
	}
}
